<template>
  <view class="custom-tabbar">
    <view class="tabbar-list">
      <view
        v-for="(tab, index) in tabs"
        :key="index"
        class="tabbar-item"
        :class="{ active: currentIndex === index }"
        @click="switchTab(index, tab.pagePath)"
      >
        <view class="tabbar-icon">
          <text class="icon-text">{{ tab.icon }}</text>
        </view>
        <text class="tabbar-text">{{ tab.text }}</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'

interface TabItem {
  pagePath: string
  text: string
  icon: string
}

const props = defineProps<{
  currentIndex: number
}>()

const emit = defineEmits<{
  tabChange: [index: number]
}>()

const tabs = ref<TabItem[]>([
  {
    pagePath: '/pages/index/index',
    text: '首页',
    icon: '🏠'
  },
  {
    pagePath: '/pages/devices/index',
    text: '设备',
    icon: '🏢'
  },
  {
    pagePath: '/pages/work-orders/index',
    text: '工单',
    icon: '📝'
  },
  {
    pagePath: '/pages/alerts/index',
    text: '告警',
    icon: '🔔'
  },
  {
    pagePath: '/pages/profile/index',
    text: '我的',
    icon: '👤'
  }
])

const currentIndex = ref(props.currentIndex)

const switchTab = (index: number, pagePath: string) => {
  if (index === currentIndex.value) return

  currentIndex.value = index
  emit('tabChange', index)

  uni.switchTab({
    url: pagePath
  })
}

// 获取当前页面路径来确定激活状态
const getCurrentPageIndex = () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const currentRoute = '/' + currentPage.route

  return tabs.value.findIndex(tab => tab.pagePath === currentRoute)
}

onMounted(() => {
  const index = getCurrentPageIndex()
  if (index !== -1) {
    currentIndex.value = index
  }
})
</script>

<style lang="scss" scoped>
.custom-tabbar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #ffffff;
  border-top: 1rpx solid #e8e8e8;
  padding: 16rpx 0 32rpx;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);
  z-index: 999;
}

.tabbar-list {
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 100rpx;
}

.tabbar-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 8rpx 16rpx;
  min-width: 120rpx;
  transition: all 0.3s ease;

  &.active {
    .tabbar-icon {
      transform: scale(1.1);
    }

    .tabbar-text {
      color: #52c41a;
      font-weight: 500;
    }
  }

  &:active {
    transform: scale(0.95);
  }
}

.tabbar-icon {
  width: 48rpx;
  height: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8rpx;
  transition: all 0.3s ease;

  .icon-text {
    font-size: 36rpx;
    line-height: 1;
  }
}

.tabbar-text {
  font-size: 24rpx;
  color: #7A7E83;
  line-height: 1;
  transition: all 0.3s ease;
}
</style>